using System.Globalization;
using Avalonia.Data;
using Avalonia.Data.Converters;

namespace Bread.Mvc.Avalonia;

public abstract class EnumToBoolConverter<T> : IValueConverter where T : unmanaged, Enum
{
    // 使用字典而不是反射来映射枚举值
    private readonly Dictionary<string, int> _valueMap;

    public EnumToBoolConverter()
    {
        _valueMap = new Dictionary<string, int>(StringComparer.OrdinalIgnoreCase);
        InitializeValueMap();
    }

    private void InitializeValueMap()
    {
        string enumName = typeof(T).Name;

        foreach (T value in Enum.GetValues<T>()) {
            // 添加完整格式的键
            string fullKey = $"{enumName}.{value}";
            _valueMap[fullKey] = System.Convert.ToInt32(value);

            // 添加简写格式的键（可选）
            string shortKey = value.ToString();
            if (!_valueMap.ContainsKey(shortKey)) {
                _valueMap[shortKey] = System.Convert.ToInt32(value);
            }
        }
    }

    public object Convert(object? value, Type targetType, object? parameter, CultureInfo culture)
    {
        if (value == null || parameter == null)
            return false;

        // 获取枚举类型名称和值名称
        string paramString = parameter.ToString() ?? string.Empty;
        if (string.IsNullOrWhiteSpace(paramString))
            return false;

        // 查找目标值
        if (_valueMap.TryGetValue(paramString, out int targetValue)) {
            return CompareEnumValues(value, targetValue);
        }

        return false;
    }

    public object ConvertBack(object? value, Type targetType, object? parameter, CultureInfo culture)
    {
        return BindingOperations.DoNothing;
    }

    private bool CompareEnumValues(object enumValue, int targetValue)
    {
        if (enumValue is T specificEnum) {
            int currentValue = System.Convert.ToInt32(specificEnum);
            return currentValue == targetValue;
        }

        if (enumValue is Enum generalEnum && enumValue.GetType() == typeof(T)) {
            int currentValue = System.Convert.ToInt32(generalEnum);
            return currentValue == targetValue;
        }

        return false;
    }
}